<!DOCTYPE html>
<html>

<head>
    <title></title>
    <meta charset="UTF-8">
</head>

<body>
    <!-- <input  type="text" id="content">
<button  onclick="exampleSocket.send( document.getElementById('content').value )">发送</button> -->
    <div id="app">
        <section>
            <input type="text" v-model='message' name="" value=""><br>
            <input type="text" v-model="username" name="" value=""><br>
        </section>

        <button type="button" v-on:click="sendMessage()">发送</button>
        <button type="button" @click="closeChat()" name="button">关闭</button>
        <button type="button" @click="startWs()" name="button">开启</button>
        <section v-for="item in info" style="border:1px solid #DDDDDD;">
            <p>{{ item.username }}说：</p>
            <p>内容：{{ item.msg }}</p>
            <p>时间：{{ item.time }}</p>
        </section>

    </div>

    <script src="http://cdn.bootcss.com/vue/2.1.6/vue.js" charset="utf-8"></script>
    <script type="text/javascript">
        window.onload = function() {
            var exampleSocket = new WebSocket("ws://0.0.0.0:9501");
            var app = new Vue({
                el: '#app',
                data: {
                    username: '二大爷',
                    message: '早啊',
                    info: [{
                        time: '1992-01-01',
                        'msg': 'test',
                        'username': 'test'
                    }],
                    exampleSocket: exampleSocket,
                },
                methods: {
                    startWs: function() {
                        this.exampleSocket = new WebSocket("ws://0.0.0.0:9501");
                    },
                    sendMessage: function() {
                        this.sendFormat(this.message);
                        this.message = '';
                    },
                    closeChat: function() {
                        this.sendFormat('走了，回聊');
                        this.exampleSocket.close();
                    },
                    sendFormat: function(msg) {
                        var json = {
                            'time': '刚刚',
                            'msg': msg,
                            'username': this.username
                        };
                        json = JSON.stringify(json);
                        this.exampleSocket.send(json);
                    }
                }
            })

            app.exampleSocket.onopen = function(event) {
                // exampleSocket.send("进入聊天室^_^");
                console.log("进入聊天室^_^");
            };
            app.exampleSocket.onmessage = function(event) {
                console.log(event.data);
                var msg = JSON.parse(event.data);
                app.info.push(msg);
            }
        }
    </script>

</body>

</html>
